using System;
using Microsoft.SPOT;
using System.IO.Ports;
using System.Text;

namespace Netduino4Fun.DesktopAssistant.Netduino.PC
{
    public class SerialConnection : IConnection
    {
        SerialPort serialPort;

        public SerialConnection()
        {
            this.serialPort = new SerialPort(Configuration.SerialPort.PortName,
                                                Configuration.SerialPort.BaudRate, Configuration.SerialPort.Parity,
                                                Configuration.SerialPort.DataBits, Configuration.SerialPort.StopBits);
            this.serialPort.Handshake = Configuration.SerialPort.Handshake;
            this.serialPort.ReadTimeout = Configuration.SerialPort.ReadTimeout;
            this.serialPort.WriteTimeout = Configuration.SerialPort.WriteTimeout;
        }



        public void Open()
        {
            this.serialPort.Open();
        }


        public void Write(byte[] data)
        {
            if (!this.serialPort.IsOpen)
                return;
            
            this.serialPort.Write(data, 0, data.Length);
        }

        public void WriteLine(string data)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(data + "\r\n");
            Write(buffer);
        }

        public string Read()
        {
            if (!this.serialPort.IsOpen)
                return null;
            
            byte[] buffer = new byte[256];
            int count = this.serialPort.Read(buffer, 0, 255);
            
            char[] chars = Encoding.UTF8.GetChars(buffer);
            return new string(chars);
        }

        public string ReadLine()
        {
            string line = string.Empty;
            
            string s;

            do
            {
                s = Read();
                if (s == string.Empty)
                    continue;

                char end = s[s.Length - 1];
                if (end == '\r' || end == '\n')
                    break;

                line += s;
            } while (true);

            return line;
        }
    }
}
